import fs from 'fs-extra';
import path from 'path';
import { TransformConfig } from './types';

export class ConfigManager {
  private configPath: string;

  constructor(configPath: string) {
    this.configPath = configPath;
  }

  async loadConfig(): Promise<TransformConfig> {
    try {
      if (await fs.pathExists(this.configPath)) {
        const config = await import(path.resolve(this.configPath));
        return this.validateConfig(config.default || config);
      }
    } catch (error) {
      console.warn(`Failed to load config from ${this.configPath}:`, error);
    }
    
    return this.getDefaultConfig();
  }

  async createDefaultConfig(): Promise<void> {
    const defaultConfig = this.getDefaultConfig();
    const configContent = `module.exports = ${JSON.stringify(defaultConfig, null, 2)}`;
    
    await fs.ensureDir(path.dirname(this.configPath));
    await fs.writeFile(this.configPath, configContent, 'utf8');
  }

  private getDefaultConfig(): TransformConfig {
    return {
      framework: 'react',
      typescript: true,
      rules: {
        pages: {
          transformLifecycle: true,
          transformData: true,
          transformMethods: true,
        },
        components: {
          transformProps: true,
          transformEvents: true,
          transformSlots: true,
        },
        apis: {
          transformWxAPI: true,
          customAPIMapping: {
            'wx.navigateTo': 'Taro.navigateTo',
            'wx.request': 'Taro.request',
            'wx.showToast': 'Taro.showToast',
          },
        },
        styles: {
          transformWXSS: true,
          transformCSSVars: true,
        },
      },
      output: {
        generateTypes: true,
        generateDocs: true,
        prettier: true,
      },
      ignore: [
        'node_modules/**',
        'dist/**',
        'build/**',
        '**/*.test.*',
        '**/*.spec.*',
      ],
    };
  }

  private validateConfig(config: any): TransformConfig {
    // 简单的配置验证
    if (!config.framework || !['react', 'vue', 'vue3'].includes(config.framework)) {
      config.framework = 'react';
    }
    
    if (typeof config.typescript !== 'boolean') {
      config.typescript = true;
    }
    
    return config as TransformConfig;
  }
} 